﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SaiLing.Paging;

namespace SaiLing
{
    public static class PageLinqExtensions
    {
        public static PagedList<T> ToPagedList<T>(this IQueryable<T> allItems, int pageIndex, int pageSize)
        {
            if (pageIndex < 1)
                pageIndex = 1;
            var itemIndex = (pageIndex - 1) * pageSize;
            var pageOfItems = allItems.Skip(itemIndex).Take(pageSize);
            var totalItemCount = allItems.Count();
            return new PagedList<T>(pageOfItems, pageIndex, pageSize, totalItemCount);
        }

        public static PagedList<T> ToPagedList<T>(this IEnumerable<T> allItems, int pageIndex, int pageSize)
        {
            if (pageIndex < 1)
                pageIndex = 1;
            var itemIndex = (pageIndex - 1) * pageSize;
            var totalItemCount = allItems.Count();
            var pageOfItems = allItems.Skip(itemIndex).Take(pageSize);
          
            return new PagedList<T>(pageOfItems, pageIndex, pageSize, totalItemCount);
        }

        public static PagedList<T> ToPagedList<T, TS>(this IEnumerable<T> allItems, int pageIndex, int pageSize, Func<T, TS> orderByExpression, bool isDesc = true)
        {
            if (pageIndex < 1)
                pageIndex = 1;
            var itemIndex = (pageIndex - 1) * pageSize;

            var pageOfItems = (IOrderedEnumerable<T>)allItems.Skip(itemIndex).Take(pageSize);
            pageOfItems = isDesc ? pageOfItems.ThenByDescending(orderByExpression) : pageOfItems.ThenBy(orderByExpression);
            var totalItemCount = allItems.Count();
            return new PagedList<T>(pageOfItems, pageIndex, pageSize, totalItemCount);
        }

        public static Task<PageData<T>> ToPageData<T>(this IEnumerable<T> allItems, int pageIndex, int pageSize)
        {
            var page = allItems.ToPagedList(pageIndex, pageSize);
            var paging = new Paging.Paging()
            {
                Current = page.CurrentPageIndex,
                PageNext = page.CurrentPageIndex + 1,
                PagePrevious = page.CurrentPageIndex - 1,
                PageSize = page.PageSize,
                TotalItems = page.TotalItemCount
            };
            return Task.FromResult<PageData<T>>(new PageData<T>
            {
                Paging = paging,
                List = page.List.ToList(),
            });
        }
    }
}
